#!/bin/bash
# Time: 2024-09-09 10:55:55
# Desc: 将check目录下的测试脚本挨个执行
# 1、测试脚本均以test-为前缀的可执行文件，本脚本将这些测试脚本找出来并挨个执行
# 2、测试结果汇总到check/result.log文件中

g_test_file="$(realpath "$0")"
g_top_dir="$(dirname "$(dirname "$g_test_file")")"

do_upgrade_kernel_devel() {
    # 如果是测试镜像
    #     检查镜像是否有安装devel包，有就不动
    #     没有安装devel包就安装运行内核的devel包
    # 如果是测试内核
    #     在更新内核时将devel包删掉，安装新内核对应的devel包

    rpm -qa | grep kernel
    # 有安装devel包则不重复安装，就算devel包版本和内核不一致，就是镜像有问题，应该提缺陷单跟踪
    if rpm -qa | grep "^kernel[-tlinux4]*-devel-"; then
        echo "the kernel devel package installed"
        return 0
    fi

    kernel_headers=$(rpm -qa | grep "^kernel.*headers")
    if [ -n "$kernel_headers" ]; then
        yum remove -y "$kernel_headers"
    fi

    if uname -r | grep tlinux4; then
        kernel_version="$(uname -r | sed "s|-tlinux[0-9]-|.|g")"
        kernel_name="kernel-tlinux4"
    else
        kernel_version="$(uname -r)"
        kernel_name="kernel"
    fi
    if grep -iq "OpenCloudOS.*Stream" /etc/os-release; then
        release_suffix="ocs"
    elif grep -iq "OpenCloudOS" /etc/os-release; then
        release_suffix="oc$(grep "^VERSION=" /etc/os-release | grep -o "[0-9]" | head -n 1)"
    elif grep -iq "TencentOS" /etc/os-release; then
        release_suffix="tl$(grep "^VERSION=" /etc/os-release | grep -o "[0-9]" | head -n 1)"
    else
        return 1
    fi
    kernel_devel_need="${kernel_name}-devel-${kernel_version}.${release_suffix}"
    kernel_headers_need="${kernel_name}-headers-${kernel_version}.${release_suffix}"
    echo "kernel_version=$kernel_version"
    echo "kernel_devel_need=$kernel_devel_need"
    echo "kernel_headers_need=$kernel_headers_need"
    if yum install -y "$kernel_devel_need" "$kernel_headers_need"; then
        echo "install kernel devel success"
    else
        echo "install kernel devel fail"
        yum list --showduplicate "${kernel_name}-devel"
        yum list --showduplicate "${kernel_name}-headers"
        return 1
    fi

    return 0
}

init_env() {
    cd "$g_top_dir" || return 1

    which git >/dev/null 2>&1 || yum install -y git
    git clean -fdx
    do_upgrade_kernel_devel || return 1
    which gcc >/dev/null 2>&1 || yum install -y gcc
    which make >/dev/null 2>&1 || yum install -y make

    return 0
}

main() {
    local _main_ret=0

    init_env || return 1

    for f in "$g_top_dir"/check/test-*; do
        if [ -x "$f" ]; then
            echo "try run test file $f"
        else
            echo "file $f can not execute, ignore"
            continue
        fi
        if "$f"; then
            echo "execute $f success"
        else
            echo "execute $f fail"
            _main_ret=1
        fi
    done
    echo "===== tsuite self test result summary ====="
    cat "$g_top_dir/check/result.log"

    return $_main_ret
}

main
